import { DeleteOutlined, EditOutlined, PlayCircleOutlined, PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import {
  FooterToolbar,
  PageContainer,
  ProTable,
} from '@ant-design/pro-components';
import { Badge, Button, Popconfirm, message } from 'antd';
import React, { useRef, useState } from 'react';
import { batchDelCase, countCase, execute, getStressCasePage } from './service';
import { history, useModel, useRequest, useSearchParams } from '@umijs/max';
import { pageModule } from '../module/service';
import { getEnvPage } from '@/pages/common-menu/environment/service';

const handleRemove = async (idList: any[], moduleId: any, projectId: any) => {
  const hide = message.loading('正在删除');
  if (!idList) return true;

  try {
    const res = await batchDelCase({
      idList,
      moduleId,
      projectId,
    });
    hide();
    if (res.code == 0) {
      message.success('删除成功，即将刷新');
      return true;
    }
    return false
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const RenderBadge = ({ active = false, moduleId }: {
  active: boolean,
  moduleId: number
}) => {

  const { initialState } = useModel('@@initialState');

  const { data: moduleTotal } = useRequest(() => {
    return countCase({ moduleId, projectId: initialState?.currentProject?.id })
  }, {})

  return (
    <Badge
      count={moduleTotal}
      style={{
        marginBlockStart: -2,
        marginInlineStart: 4,
        color: active ? '#1890FF' : '#999',
        backgroundColor: active ? '#E6F7FF' : '#eee',
      }}
    />
  );
};

const TableList: React.FC = () => {
  const [searchParams, setSearchParams] = useSearchParams()
  const moduleId = searchParams.get("moduleId")
  const actionRef = useRef<ActionType>();
  const [selectedRowsState, setSelectedRows] = useState<any[]>([]);
  const { initialState } = useModel('@@initialState');

  const defaultModuleId = useRef()

  const isLoadModuled = useRef(false)

  const { data: moduleData, run: getModule } = useRequest(() => {
    return pageModule({ current: 1, pageSize: 100, projectId: initialState?.currentProject?.id })
  }, {
    manual: true, onSuccess(data) {
      isLoadModuled.current = true
      if (!moduleId) {
        setSearchParams({
          moduleId: data?.currentData?.[0]?.id
        })
        defaultModuleId.current = data?.currentData?.[0]?.id
      }
    }
  })

  const columns: ProColumns<any>[] = [
    {
      title: '用例名称',
      dataIndex: 'name',
      fixed: 'left',
    },
    {
      title: '模块名称',
      dataIndex: 'moduleId',
      valueType: 'select',
      hideInSearch: true,
      valueEnum(row) {
        const map = {}
        moduleData?.currentData?.forEach((item: any) => {
          map[item.id] = item.name
        })
        return map
      },
    },
    {
      title: '压力源类型',
      dataIndex: 'stressSourceType',
      valueType: 'select',
      valueEnum: {
        SIMPLE: { text: '在线自定义' },
        JMX: { text: '本地上传JMX脚本' },
      }
    },
    {
      title: '所属环境',
      dataIndex: 'environmentId',
      valueType: 'select',
      request: async () => {
        const res = await getEnvPage({ current: 1, pageSize: 100 })

        return res?.data?.currentData?.map((item: any) => ({
          label: item?.name,
          value: item?.id,
        }))
      }
    },
    {
      title: '描述',
      dataIndex: 'description',
      hideInSearch: true,
    },
    {
      title: '创建时间',
      dataIndex: 'gmtCreate',
      valueType: 'dateTime',
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '修改时间',
      dataIndex: 'gmtModified',
      valueType: 'dateTime',
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      fixed: 'right',
      render: (_, record: any) => [
        <a
          key="config"
          onClick={() => {
            history.push('/stress-test/case-form?id=' + record?.id)
          }}
        >
          <EditOutlined /> 编辑
        </a>,
        <Popconfirm key='run' title={`是否要运行此用例？`} onConfirm={async () => {
          const res = await execute({
            projectId: initialState?.currentProject?.id,
            id: record?.id,
          })
          if (res.code == 0) {
            message.success({
              content: '压测用例执行成功! 即将前往压测报告页面~',
              duration: 0.8,
            }).then(() => {
              history.push(`/report/stress-test?caseId=${record?.id}`)
            })
            return true
          }
          return false
        }}>
          <a><PlayCircleOutlined /> 执行</a>
        </Popconfirm>,
        <Popconfirm key='del' title={`是否要删除此用例？`} onConfirm={async () => {
          const res = await handleRemove([record?.id], moduleId, initialState?.currentProject?.id);
          if (res) {
            actionRef.current?.reload()
            setSelectedRows([]);
          }
        }}>
          <a><DeleteOutlined /> 删除</a>
        </Popconfirm>
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable<any>
        actionRef={actionRef}
        rowKey="id"
        scroll={{x: 'max-content'}}
        search={{
        }}
        toolbar={{
          menu: {
            type: 'tab',
            activeKey: moduleId as any,
            items: moduleData?.currentData?.map((item: any) => ({
              key: item.id + '',
              label: <span>{item.name}
                <RenderBadge moduleId={item.id} active={moduleId == item.id} />
              </span>,
            })),
            onChange: (key) => {
              actionRef.current?.reload()
              setSearchParams({
                moduleId: key as any || ''
              })
            },
          },
          actions: [
            <Button
              key="adCase"
              type='primary'
              onClick={() => {
                history.push('/stress-test/case-form')
              }}
            >
              <PlusOutlined /> 新建压测用例
            </Button>,
          ],
        }}
        request={async ({ pageSize, current, ...params }) => {
          let moduleData = {} as any
          if (!isLoadModuled.current) {
            moduleData = await getModule()
          }
          const res = await getStressCasePage({
            current,
            pageSize,
            ...params,
            moduleId: moduleId || defaultModuleId.current,
            projectId: initialState?.currentProject?.id
          })
          const total = res?.data?.totalRecords || 0
          const data = res?.data?.currentData || []
          return {
            data,
            total,
          }
        }}
        columns={columns}
        rowSelection={{
          selectedRowKeys: selectedRowsState?.map((item: any) => item.id),
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowsState.length}
              </a>{' '}
              项 &nbsp;&nbsp;
              {/* <span>
                服务调用次数总计 {selectedRowsState.reduce((pre, item) => pre + item.callNo!, 0)} 万
              </span> */}
            </div>
          }
        >
          <Popconfirm key='del' title={`是否要批量删除 ${selectedRowsState.length} 条？`} onConfirm={async () => {
            const res = await handleRemove(selectedRowsState?.map((item: any) => item.id), moduleId, initialState?.currentProject?.id);
            if (res) {
              actionRef.current?.reload()
              setSelectedRows([]);
            }
          }}>
            <Button danger>
              批量删除
            </Button>
          </Popconfirm>
        </FooterToolbar>
      )}
    </PageContainer>
  );
};

export default TableList;
